#!/usr/bin/env bash

SP_MIN_MEM=512m
SP_MAX_MEM=1024m

SCRIPT="$0"
# SCRIPT may be an arbitrarily deep series of symlinks. Loop until we have the concrete path.
while [ -h "$SCRIPT" ] ; do
  ls=`ls -ld "$SCRIPT"`
  # Drop everything prior to ->
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    SCRIPT="$link"
  else
    SCRIPT=`dirname "$SCRIPT"`/"$link"
  fi
done

# some Java parameters
JAVA=`which java 2>/dev/null`
if [[ $JAVA_HOME != "" ]]; then
    JAVA=$JAVA_HOME/bin/java
fi
if test -z "$JAVA"; then
    echo "No java found in the PATH. Please set JAVA_HOME."
    exit 1
fi

APP_HOME=`dirname "$SCRIPT"`
export APP_HOME=`cd "$APP_HOME"/..; pwd`

SP_CLASSPATH=$APP_HOME/conf:$APP_HOME/lib/*

MAIN_CLASS="yanagishima.server.YanagishimaServer"
APP_ARGS="-conf $APP_HOME/conf"
DEF_APP_NAME="yanagishima"

#java opts config
SP_OPTS="-Dapp.home=$APP_HOME -DAPP_NAME=$DEF_APP_NAME -Djava.library.path=$APP_HOME/conf"
SP_OPTS="$SP_OPTS -Xms${SP_MIN_MEM} -Xmx${SP_MAX_MEM}"

if [ ! -d "$APP_HOME/logs" ]
then
    mkdir -p $APP_HOME/logs
fi

COMMAND=$1

start(){
  echo "starting $DEF_APP_NAME ..."
  nohup $JAVA $SP_OPTS -cp $SP_CLASSPATH $MAIN_CLASS $APP_ARGS >/dev/null 2>&1 &
  echo "please see the log --> '$APP_HOME/logs/$DEF_APP_NAME.log' or 'ps -ef|grep Application'"
  echo "$DEF_APP_NAME has started! "
}

run(){
  echo "run $DEF_APP_NAME server..."
  $JAVA $SP_OPTS -cp $SP_CLASSPATH $MAIN_CLASS $APP_ARGS
}

stop(){
    echo "stop ..."
    warningpid=`jps -l|grep $MAIN_CLASS | cut -f 1 -d " "`
    echo "$MAIN_CLASS process's pid is $warningpid"

    if [ $warningpid ]
        then
            jps -l|grep $MAIN_CLASS | cut -f 1 -d " " |xargs  kill -15
            echo "$MAIN_CLASS [$warningpid] is stoped!"
        else
            echo "$MAIN_CLASS stop failed!"
    fi
}

status(){
     warningpid=`jps -l|grep $MAIN_CLASS | cut -f 1 -d " "`
     if [ $warningpid ]
         then
            echo "$MAIN_CLASS [$warningpid] is running "
         else
            echo "$MAIN_CLASS is not running"
     fi
}

docommand() {
    case "$COMMAND" in
        'start')
            start
            ;;
        'run')
            run
            ;;

        'stop')
            stop
            ;;

        'restart')
            stop;
            sleep 5
            start;
            ;;

        'status')
            status
            ;;

		*)
		 echo "usage: [start|run|stop|restart|status|log]"
		;;
    esac
}
docommand "$@"
exit 0